import React, {useState, useEffect} from 'react';
import {observer} from 'mobx-react';
import ProductsStore from './store/ProductsStore.js';
import Loading from './Loading.jsx';

const products = [
	{id: 1, name: '产品1'},
	{id: 2, name: '产品2'},
	{id: 3, name: '产品3'},
	{id: 4, name: '产品4'},
	{id: 5, name: '产品5'},
];

const loadProducts = () => {
	return new Promise(resolve => {
		if (!ProductsStore.isLoad) {
			ProductsStore.loading = true;
			// 模拟 1000 秒延时获取数据
			setTimeout(() => {
				ProductsStore.loading = false;
				ProductsStore.products = products;
				ProductsStore.isLoad = true;
			}, 3000);
		}
	});
};

const ProductsListContent = () => {

};

const Products = () => {
	
	useEffect(() => {
		loadProducts();
	}, []);
	
	const forceUpdate = () => {
		if (!ProductsStore.loading) {
			ProductsStore.isLoad = false;
			loadProducts();
		}
	};
	
	return <>
		<Loading show={ProductsStore.loading} text={'加载商品中...'}/>
		<div className={'products-list'}>
			{ProductsStore.products.length > 0 ? ProductsStore.products.map(product => {
				return <div key={`product-for-${product.id}`}>{product.id}#{product.name}</div>;
			}) : '暂无商品'}
			{ProductsStore.isLoad && <button type={'button'} onClick={e => forceUpdate()}>强制刷新</button>}
		</div>
	</>;
};

export default observer(Products);